<?php 
/**
 * Plugin Name:Wp Form Submission
 * Author:Wayne
 * Version:1.0.0
 */

register_activation_hook( __FILE__, 'wp_learn_setup_table' );

function wp_learn_setup_table()
{
	global $wpdb;

	$table_name = $wpdb->prefix.'form_submission';

	$sql = "CREATE TABLE $table_name (
		id mediumint(9) NOT NULL AUTO_INCREMENT,
		name varchar (100) NOT NULL,
		email varchar (100) NOT NULL,
		PRIMARY KEY (id))
		";

		require_once (ABSPATH . 'wp-admin/includes/upgrade.php');
		dbDelta( $sql );
	
}

//register_rest_route必须在rest api init钩子下注册 

add_action( 'rest_api_init', 'wp_learn_register_routes',4 );

function wp_learn_register_routes()
{

	//premission_callback 可以增加权限的 比方说可以设置特定的权限要求比方说 edit_posts 下面的人能
	register_rest_route( 
		'wp-learn-form-submission-api/v1', 
		'/form-submissions', 
		array(
			'methods'  => 'GET',
			'callback'  => 'wp_learn_rest_get_form_submissions',
			//'permission_callback'  => 'wp_learn_permission'
			'permission_callback'  => '__return_true'
		) );

	register_rest_route( 
		'wp-learn-form-submission-api/v2', 
		'/form-submissions', 
		array(
			'methods'  => 'POST',
			'callback'  => 'wp_learn_rest_create_form_submissions',
			'permission_callback'  => '__return_true'
		) );

	//for single 
	register_rest_route( 
		'wp-learn-form-submission-api/v1', 
		'/form-submission/(?P<id>[\d]+)', 
		array(
			'methods'  => 'GET',
			'callback'  => 'wp_learn_rest_get_form_submission',
			'permission_callback'  => '__return_true'
		) );
	
}

//用_fields=id,title,content  可以实现查询特定字段
//查询特定的single 内容的时候要用到正则查询来实现动态id 

function wp_learn_permission() {

	return current_user_can( 'edit_posts' );
}

function wp_learn_rest_get_form_submissions() {
	global $wpdb;

	$table_name = $wpdb->prefix.'form_submission';

	$results = $wpdb->get_results("SELECT * FROM $table_name");

	return $results;
    
}

function wp_learn_rest_get_form_submission($request) {
	$id = $request['id'];
	global $wpdb;

	$table_name = $wpdb->prefix.'form_submission';

	$results = $wpdb->get_results("SELECT * FROM $table_name WHERE id = $id");

	return $results[0];

}

function wp_learn_rest_create_form_submissions( $request ) {

	global $wpdb;

	$table_name = $wpdb->prefix.'form_submission';

	$rows = $wpdb->prefix . 'form_submissions';

	$rows = $wpdb->insert($table_name,array(
		'name'  => $request['name'],
		'email'  => $request['email']

	)); 

	return 'Form submission added'; 


}

